package com.gongj.secuitydb.config;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.gongj.secuitydb.entity.Menu;
import com.gongj.secuitydb.entity.Role;
import com.gongj.secuitydb.service.MenuService;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    MenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl(); //用户请求地址
        List<Menu> allMenu = menuService.getAllMenu(); //所有菜单
        for (Menu menu : allMenu) {
            //进行匹配，如果匹配成功,就返回该请求需要的角色
            if (pathMatcher.match(menu.getPath(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                String[] rolesStr = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    rolesStr[i] = roles.get(i).getNameEN();
                }
                return SecurityConfig.createList(rolesStr);
            }
        }
        //如果没有匹配成功，就说明该请求不需要拥有角色就能访问，给它一个标识符。
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

}
